-module(echo).
-export([start/0, start/1]).

-define(TCP_OPTIONS,[list, {packet, 0}, {active, false}, {reuseaddr, true}]).
-record(player, {name=none, socket, mode}).

start() ->
	listen(3010).
	
start(Port) ->
	listen(Port).
	
listen(Port) ->
	% create a list to manage client processes
	Pid = spawn(fun() -> manage_clients([]) end),
	register(clientmanager, Pid),
	{ok, Listener} = gen_tcp:listen(Port, ?TCP_OPTIONS),
	accept(Listener).

accept(Listener) ->
	{ok, Socket} = gen_tcp:accept(Listener),
	% add the new socket to the list of client processes
	clientmanager ! {connect, Socket},
	spawn(fun() -> loop(Socket) end),
	accept(Listener).

loop(Socket) ->
	case gen_tcp:recv(Socket, 0) of
		{ok, Data} ->
			clientmanager ! {data, Data},
			loop(Socket);
		{error, closed} ->
			ok
	end.
	
manage_clients(Sockets) ->
	receive
		{connect, Socket} ->
			io:fwrite("New Socket connection: ~p~n", [Socket]),
			NewSockets = [Socket | Sockets];
		{data, Data} ->
			io:fwrite("Sending data: ~p~n", [Data]),
			send_data(Sockets, Data),
			NewSockets = Sockets
	end,
	manage_clients(NewSockets).
	
send_data(Sockets, Data) ->
	SendData = 	fun(Socket) -> 
					gen_tcp:send(Socket, Data) 
				end,
	lists:foreach(SendData, Sockets).

